package com.hrzyit.whistle.cases.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.github.piasy.rxandroidaudio.AudioRecorder
import com.github.piasy.rxandroidaudio.RxAudioPlayer
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.base.utils.AudioRecorderUtils
import com.hrzyit.base.utils.DateUtils
import com.hrzyit.base.utils.IMUtils
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.data.bean.AudioInfo
import com.hrzyit.whistle.cases.data.bean.UploadInfo
import com.hrzyit.whistle.cases.event.ReturnAudioRecordEvent
import com.hrzyit.whistle.cases.injection.component.DaggerCaseCenterComponent
import com.hrzyit.whistle.cases.injection.component.DaggerCaseInfoComponent
import com.hrzyit.whistle.cases.injection.module.UploadModule
import com.hrzyit.whistle.cases.presenter.RecordAudioPresenter
import com.hrzyit.whistle.cases.presenter.view.RecordAudioView
import com.hrzyit.whistle.cases.widgets.CaseApplyClosePopup
import com.hrzyit.whistle.cases.widgets.SaveAudioConfirmPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_record_audio.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.support.v4.toast
import java.io.File

/**
 * 录制语音 Fragment
 * @author YangWei
 * @date 2019/4/12
 */
class RecordAudioFragment : BaseMvpFragment<RecordAudioPresenter>(),
    RecordAudioView {

    /**
     * Activity 结果回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

    companion object {
        const val TAG = "RecordAudioFragment"
        const val RECORD_TIME = 60 // 录音时间
    }

    /**
     * 保存语音文件回调
     */
    override fun onUploadRecordAudioResult(result: UploadInfo) {

        result?.let {
            // 关闭弹出窗口
            audioPopup.dismiss()
            // 关闭语音描述 Fragment
            EventBus.getDefault().post(ReturnAudioRecordEvent(result))

            // 返回新建案件界面
            activity.finish()
        }

    }

    private lateinit var activity: Activity

    // 录音文件
    private lateinit var mAudioFile: File

    // 动态权限组件 RxPermissions
    private lateinit var mPermissions: RxPermissions

    // 录音文件地址，返回到新建案件 Activity 进行保存
    private lateinit var mAudioFilePath: String


    private var mAudioRecorderUtils: AudioRecorderUtils? = null
    // 录音文件
    private var voiceFilePath: String? = null
    private var voiceTime: Long? = 0L

    // 弹出窗口
    private lateinit var audioPopup: BasePopupView

    // 保存音频录制结果窗口
    private lateinit var saveAudioConfirmPopup: SaveAudioConfirmPopup

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as Activity
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        // 加载 fragment_record_audio 视图
        return inflater.inflate(R.layout.fragment_record_audio, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
    }

    /**
     * 初始化 Fragment 视图
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        // 创建权限对象
        mPermissions = RxPermissions(activity)

        // 初始化录音文件路径
        createTempFile("file.amr")
        mAudioFilePath = mAudioFile.absolutePath

        // 构建录音工具类
        mAudioRecorderUtils = AudioRecorderUtils(mAudioFilePath)

        //录音回调
        mAudioRecorderUtils!!.setOnAudioStatusUpdateListener(
            object : AudioRecorderUtils.OnAudioStatusUpdateListener {

                //录音中....db为声音分贝，time为录音时长
                override fun onUpdate(db: Double, time: Long) {
                    mRecAnimationIv.drawable.level = (3000 + 6000 * db / 100).toInt()
                    mRecTimeTv.text = IMUtils.long2String(time)
                }

                //录音结束，filePath为保存路径
                override fun onStop(time: Long, filePath: String?) {
                    mRecTimeTv.text = IMUtils.long2String(0)
                    voiceFilePath = filePath
                    voiceTime = time

                    val audioInfo = AudioInfo()
                    audioInfo.voiceFilePath = voiceFilePath
                    audioInfo.voiceTime = voiceTime!!

//                    EventBus.getDefault().post(messageInfo)
                    // TODO 2019/4/24 - 待完成内容：语音描述确认窗口
                    saveAudioConfirmPopup = SaveAudioConfirmPopup(context!!)
                    saveAudioConfirmPopup.audioInfo = audioInfo
                    saveAudioConfirmPopup.recordAudioPresenter = mPresenter
                    audioPopup = XPopup.Builder(context)
                        .asCustom(saveAudioConfirmPopup)
                        .show()
                }

                override fun onError() {
                    mRecTimeTv!!.text = IMUtils.long2String(0)
//                    mEditText!!.visibility = View.VISIBLE
                }

                override fun onCancel(time: Long) {
                    mRecTimeTv.text = IMUtils.long2String(0)
                    mRecAnimationIv.drawable.level = 0
                }
            }
        )

        mRecordToSayBtn!!.setOnTouchListener { v, event ->

            // 获得x轴坐标
            val x = event.x.toInt()
            // 获得y轴坐标
            val y = event.y.toInt()
            mPopVoiceText!!.visibility = View.VISIBLE

            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 按下说话
//                    mVoicePop!!.showAtLocation(v, Gravity.CENTER, 0, 0)
                    mRecordToSayBtn!!.text = "松开结束"
                    mPopVoiceText!!.text = "手指上滑，取消发送"
                    mRecordToSayBtn!!.tag = "1"
                    mAudioRecorderUtils!!.startRecord(activity as Context)

                }
                MotionEvent.ACTION_MOVE -> if (wantToCancel(x, y)) {
                    mRecordToSayBtn!!.text = "松开结束"
                    mPopVoiceText!!.text = "松开手指，取消发送"
                    mRecordToSayBtn!!.tag = "2"
                } else {
                    mRecordToSayBtn!!.text = "松开结束"
                    mPopVoiceText!!.text = "手指上滑，取消发送"
                    mRecordToSayBtn!!.tag = "1"
                }
                MotionEvent.ACTION_UP -> {
                    // 松开按钮取消或完成录音
                    if (mRecordToSayBtn!!.tag == "2") {
                        //取消录音（删除录音文件）
                        mAudioRecorderUtils!!.cancelRecord()
                    } else {
                        //结束录音（保存录音文件）
                        mAudioRecorderUtils!!.stopRecord()
                    }
                    mRecordToSayBtn!!.text = "按住说话"
                    mRecordToSayBtn!!.tag = "3"
                    mPopVoiceText!!.visibility = View.GONE
                }
            }

            true
        }
    }

    /**
     * 清除语音
     */
    private fun wantToCancel(x: Int, y: Int): Boolean {
        // 超过按钮的宽度
        if (x < 0 || x > mRecordToSayBtn!!.width) {
            return true
        }
        // 超过按钮的高度
        return y < -50 || y > mRecordToSayBtn!!.height + 50
    }


    /**
     * Dagger2 注入
     */
    override fun injectComponent() {

        DaggerCaseInfoComponent.builder()
            .activityComponent(mActivityComponent)
            .uploadModule(UploadModule())
            .build()
            .inject(this)

        mPresenter.mView = this
    }


    /**
     * 创建上传图片临时文件
     */
    private fun createTempFile(suffix: String) {
        val tempFileName = "${DateUtils.curTime}.$suffix"
        when (Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageState() -> {
                // 在存储卡中创建
                this.mAudioFile = File(Environment.getExternalStorageDirectory(), tempFileName)
            }
            else -> {
                // 在内存中创建
                this.mAudioFile = File(activity.filesDir, tempFileName)
            }
        }
    }
}